package com.itbaiyun.usercenter.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itbaiyun.usercenter.model.domain.User;
import com.itbaiyun.usercenter.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.itbaiyun.usercenter.constant.RedisConstant.RECOMMEND_USER_KET;
import static com.itbaiyun.usercenter.constant.RedisConstant.RECOMMEND_USER_TTL;

@Component
@Slf4j
public class PreCacheJob {

    @Resource
    private UserService userService;

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private RedisTemplate redisTemplate;

    //重点用户->先写死
    private List<Long> mainUserList = Arrays.asList(1L);

    //每天凌晨4点执行->预热推荐用户
    @Scheduled(cron = " 0 4 0 * * *")
    public void doCacheRecommendUser() {
//        //遍历重点用户.获得每个用户的id
//        for (Long userId : mainUserList){
//            //先从数据库查询
//            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//            Page<User> userPage = userService.page(new Page<>(1, 20), queryWrapper);
//            //缓存key
//            String key = String.format(RECOMMEND_USER_KET+":%s", userId);
//            //将查出的结果写入缓存
//            redisTemplate.opsForValue().set(key,userPage,RECOMMEND_USER_TTL, TimeUnit.MILLISECONDS);
//            ValueOperations<String, String> stringStringValueOperations = redisTemplate.opsForValue();
//        }


        //尝试获得锁
        RLock lock = redissonClient.getLock("lock:" + Thread.currentThread().getId());
        //判断是否获得锁成功
        boolean success = lock.tryLock();
        try {
            //成功则执行方法
            if (success) {
//                遍历重点用户.获得每个用户的id
                for (Long userId : mainUserList) {
                    //先从数据库查询
                    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                    Page<User> userPage = userService.page(new Page<>(1, 20), queryWrapper);
                    //缓存key
                    String key = String.format(RECOMMEND_USER_KET + ":%s", userId);
                    //将查出的结果写入缓存
                    try {
                        redisTemplate.opsForValue().set(key, userPage, RECOMMEND_USER_TTL, TimeUnit.MILLISECONDS);
                        ValueOperations<String, String> stringStringValueOperations = redisTemplate.opsForValue();
                    } catch (Exception e) {
                        log.error("缓存写入失败:", e);
                    }
                }
            }
        } catch (Exception e) {
            log.error("缓存预热失败:", e);
        } finally {
            //释放锁
            //判断释放的是不是自己的锁
            if (lock.isHeldByCurrentThread()) {
                log.info("释放锁:" + Thread.currentThread().getId());
                lock.unlock();
            }
        }
    }
}
